﻿namespace MEF_Test.Contracts
{
    using System;
    using System.Windows.Input;

    public class ActionCommand<T> : ICommand
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="ActionCommand&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="executeMethod">The execute method.</param>
            /// <param name="canExecuteMethod">The can execute method.</param>
            public ActionCommand(Action<T> executeMethod, Func<bool> canExecuteMethod)
            {
                _executeMethod = executeMethod;
                _canExecuteMethod = canExecuteMethod;
            }

            private Action<T> _executeMethod;

            private Func<bool> _canExecuteMethod;

            #region ICommand Members
            /// <summary>
            /// Invokes the delegate passed as an argument to the constructor for CanExecute
            /// </summary>
            /// <param name="parameter"></param>
            /// <returns></returns>
            public bool CanExecute(object parameter)
            {
                return _canExecuteMethod();
            }
            /// <summary>
            /// Invokes the delegate passed as an argument to the constructor for Execute
            /// </summary>
            /// <param name="parameter"></param>
            public void Execute(object parameter)
            {
                _executeMethod((T)parameter);
            }

            // This is necessary tu notify the CommandManager he's in charge of a new ICommand.
            // This is necessary for advanced features such as forcing the reevaluation of the CanExecute method !
        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }

            #endregion
        }
}
